import { Component, OnDestroy, OnInit } from "@angular/core";
import { sjgzxinModuledatas } from "../pubcomponent/pageTitle.datas";
import { CommService } from "../comm-service";

import { FormBuilder, FormGroup } from "@angular/forms";
import { MyhttpService } from "../myhttp.service";

declare var $: any;

@Component({
  template: `
  <div class="all_bg paddingTop">
    <div class="">
      <div class="marginBottom">
        <ng-container *ngIf="actionobj1.length">
          <portlet-action class="actions" [o]="actionobj1" (outhander)="actionHander($event)"></portlet-action>
        </ng-container>
      </div>
      <div class="portlet-body">
        <div class="row">
          <div class="col-lg-12" *ngIf="table_gjgl">
            <my-table [o]="table_gjgl"></my-table>
          </div>
        </div>
      </div>
    </div>
    <div class="modal fad" id="add_glModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">添加固件</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal" role="form">
              <div class="row">
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="control-label col-lg-3">
                      <require-label></require-label>
                      设备类型:</label>
                    <div class="col-lg-8">
                      <select class="form-control" id="sblxSelect" name="ccm" [(ngModel)]="uploadForm.sblx"></select>
                    </div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="control-label col-lg-3">
                      <require-label></require-label>
                      固件版本号:</label>
                    <div class="col-lg-8">
                      <input type="text" class="form-control" name="gjbbh" [(ngModel)]="uploadForm.gjbbh"/>
                      <div *ngIf="uploadForm.gjbbhwarnflag">
                        <tool-tip [o]="uploadForm.gjbbhwarntext"></tool-tip>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="control-label col-lg-3">
                      <require-label></require-label>
                      文件:</label>
                    <div class="col-lg-8" id="gjfileRoom">
                      <form-file-input [o]="fileobj_gj" (outMethod)="methodHander($event)"></form-file-input>
                      <div *ngIf="uploadForm.filewarnflag">
                        <tool-tip [o]="uploadForm.filewarntext"></tool-tip>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="control-label col-lg-3">
                      <require-label></require-label>
                      固件名称:</label>
                    <div class="col-lg-8">
                      <input type="text" class="form-control" name="gjmc" readonly [(ngModel)]="uploadForm.gjmc"/>
                    </div>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
            <button type="button" class="btn btn-primary" (click)="addsure()">确 定</button>
          </div>
        </div>
      </div>
    </div>
    </div>
  `
})
export class SbgjglComponent implements OnInit, OnDestroy {
  pagetitleobj: any;
  userinfo: any;
  sbgl_btns: any[] = ["gjglx_add", "gjglx_refresh", "gjglx_removeN"];
  actionobj1: any[] = [];
  table_gjgl: any;
  sblxList: any = [{
    code: "sczdsb",
    name: "手持终端"
  }, {
    code: "dzbqsb",
    name: "电子标签"
  }];
  sblxKeyValue: any = {
    sczdsb: "手持终端",
    dzbqsb: "电子标签"
  };
  uploadForm: any = {
    gjmc: "",  //固件名称，从固件文件中拿到
    sblx: "", //设备类型，选择
    gjbbh: "", // 输入
    gjbbhwarnflag: false,
    gjbbhwarntext: "",
    wjccbh: "", // 文件id
    filewarnflag: false,
    filewarntext: '请选择固件文件'
  };
  fileobj_gj: any;

  /**
   * 初始化按钮
   */
  initactions(): void {
    // this.commservice.getroleBtns(this.sbgl_btns, [], this.userinfo.nowroleid, "tablesbgl", (hasportbtns, hastablebtns) => {
    //   this.actionobj1 = hasportbtns;
    // });
    this.commservice.getroleBtns_not_permissions(this.sbgl_btns, [], "tablesbgl", (hasportbtns, hastablebtns) => {
      this.actionobj1 = hasportbtns;
    });
  }

  /**
   * 按钮的处理回调
   * @param e
   */
  actionHander(e: any): void {
    const fromv = e.pfrom;
    const actiontype = e.type;
    if (fromv === "tablesbgl") {
      if (actiontype === "refresh") {
        // 刷新
        this.table_gjgl = Object.assign({}, this.table_gjgl);
      } else if (actiontype === "add") {
        // 添加
        this.add_gj();
      } else if (actiontype == "removeN") {
        // 批量删除 固件
        const selectrows = $("#table_gjgl").bootstrapTable("getSelections");
        if (selectrows.length == 0) {
          this.commservice.myswal("warning", "请选择删除的数据", "", "ts", null);
          return;
        }
        this.commservice.myswal("warning", "确认删除?", "", "cz", () => {
          const removebhs = selectrows.map((item) => {
            return item.gjbh
          });
          this.removeN_gj(removebhs);
        });
      }
    }
  }

  /**
   * 添加固件
   */
  add_gj(): void {
    this.uploadForm.sblx = this.sblxList[0].code;
    $("#sblxSelect").selectpicker("val", this.sblxList[0].code);
    this.uploadForm.gjmc = "";
    this.uploadForm.gjbbh = "";
    this.uploadForm.gjbbhwarnflag = false;
    this.uploadForm.gjbbhwarntext = "";
    this.uploadForm.wjccbh = "";
    this.uploadForm.filewarnflag = false;
    this.uploadForm.filewarntext = "";
    $("#gjfileRoom .selectFile").find("input").val(""); // 显示的名字
    this.fileobj_gj["zjlx"] = "add";
    this.fileobj_gj = Object.assign({}, this.fileobj_gj);
    $("#add_glModal").modal({
      keyboard: true,
      backdrop: "static"
    })
  }

  /**
   * 批量删除
   */
  removeN_gj(removebhs: any): void {
    const url = "sjgz/gjgl/gjsc";
    this.itservice.kwPtPost(url, {
      gjbhList: removebhs
    }).subscribe(resp => {
      this.commservice.handResponse("put", url, resp, (flag, resp, flag2) => {
        if (flag) {
          if (flag2) {
            this.commservice.myswal("success", resp, "", "ts", null);
            this.table_gjgl = Object.assign({}, this.table_gjgl);
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.removeN_gj(removebhs);
        }
      });
    });
  }

  /**
   * 固件表格
   */
  inittable_gj(): void {
    const that = this;
    this.table_gjgl = {
      tableid: "table_gjgl",
      url: "sjgz/gjgl/gllb",
      reqobj: null,
      sidePagination: "server",
      pageSize: 10,
      pageList: [10, 20, 30],
      total: "totalRows",
      rows: "sbgjList",
      columns: [{
        checkbox: true
      }, {
        title: "序号",
        field: "ordernum",
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        }
      }, {
        title: "固件名称",
        field: "gjmc",
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        }
      }, {
        title: "设备类型",
        field: "sblx",
        cellStyle: function () {
          return {
            classes: 'td3'
          }
        },
        formatter: function (v) {
          return that.sblxKeyValue[v] ? that.sblxKeyValue[v] : '';
        }
      }, {
        title: "固件版本号",
        field: "gjbbh",
        cellStyle: function () {
          return {
            classes: 'td4'
          }
        }
      }, {
        title: "上传时间",
        field: "scsj",
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        }
      }]
    };
    // this.table_gjgl.pageSize = 50;
    // this.table_gjgl.pageList = [50];
    // this.table_gjgl.hiddenPageinfoLink = true;
    // this.table_gjgl.paginationLoop = true;
    // this.table_gjgl.paginationPreText = "<i class='fa fa-arrow-left'></i>上一页";
    // this.table_gjgl.paginationNextText = "下一页<i class='fa fa-arrow-right'></i>";
    // this.table_gjgl.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240;
    this.table_gjgl.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240;
  }


  createform(): void {
    $("#sblxSelect").empty();
    let str: string = "";
    this.sblxList.forEach((item) => {
      str += "<option value='" + item.code + "'>" + item.name + "</option>";
    });
    $("#sblxSelect").append(str);
    $("#sblxSelect").selectpicker({
      size: 5
    });
    this.uploadForm.sblx = this.sblxList[0].code;

    this.fileobj_gj = {
      autoup: true,
      zjlx: "add",
      attachmentDefineId: 2
    };
    $("#gjfileRoom").find(".selectFile").click(function () {
      $("#gjfileRoom").find(".ngselectFileInput").click();
    });
  }

  /**
   * 照片选择上传完毕的回调
   * @param e
   */
  methodHander(e: any): void {
    const result_code = e.flag;
    if (result_code === "success") {
      const fileid = e.fileId;
      this.uploadForm.wjccbh = fileid;
      this.uploadForm.gjmc = e.filename;
    }
  }

  /**
   * 验证+保存
   */
  addsure(): void {
    if (!this.uploadForm.gjbbh) {
      this.uploadForm.gjbbhwarnflag = true;
      this.uploadForm.gjbbhwarntext = "固件版本号不能为空";
      return
    }
    this.uploadForm.gjbbhwarnflag = false;
    this.uploadForm.gjbbhwarntext = "";
    if (!this.uploadForm.wjccbh) {
      this.uploadForm.filewarnflag = true;
      this.uploadForm.filewarntext = "请上传固件文件";
      return
    }
    this.uploadForm.filewarnflag = false;
    this.uploadForm.filewarntext = "";

    this.commservice.blockUI({
      boxed: true,
      message: "保存中...",
      zIndex: 10051,
      overlayColor: "#67809F"
    });
    const url = "sjgz/gjgl/xzgj";
    this.itservice.kwPtPost(url, {
      gjmc: this.commservice.removeSpace(true, this.uploadForm.gjmc),
      sblx: this.commservice.removeSpace(true, this.uploadForm.sblx),
      gjbbh: this.commservice.removeSpace(true, this.uploadForm.gjbbh),
      wjccbh: this.commservice.removeSpace(true, this.uploadForm.wjccbh)
    }).subscribe(resp => {
      this.commservice.handResponse("put", url, resp, (flag, resp, flag2) => {
        if (flag) {
          if (flag2) {
            this.commservice.myswal("success", resp, "", "ts", null);
            this.table_gjgl = Object.assign({}, this.table_gjgl);
            $("#add_glModal").modal("hide");
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.addsure();
        }
      });
    });
  }

  /**
   * 获取用户信息
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.userinfo = info;
      this.initactions(); //用户按钮权限
    });
  }

  constructor(private commservice: CommService,
    private itservice: MyhttpService) {

  }

  ngOnInit() {
    this.pagetitleobj = sjgzxinModuledatas.sbgjgl;
    this.getuserinfo();
    this.inittable_gj();
    this.createform();
  }

  ngOnDestroy() {

  }

}
